<?php

    class ImageController extends WebController
    {
        public $menu_selected = 'image';

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                //'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array('index','view', 'ajaxUpdatePoint', 'img', 'fixImageUrl'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('create'),
                    'users'=>array('@'),
                ),

                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('update'),
                    'expression'    =>  array($this, 'ruleModOwner'), 
                ),

                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                    'actions'=>array('admin', 'fix', 'delete', 'reviewed','social'),
                    'users'=>array('@'),
                    'expression'    =>  '$user->userInfo->isMod', 
                ),
                array('deny',  // deny all users 
                    'users'=>array('*'),
                ),
            );
        }

        public function ruleAdminOwner($user){
            if($user->isGuest) return FALSE;
            if($user->user->isAdmin) return TRUE;
            $id = Yii::app()->request->getQuery('id');
            $image = Image::model()->findByAttributes(array(
                'id' => $id,
                'user_id' => $user->id,
            ));
            return $image ? TRUE : FALSE;    
        }
        public function ruleModOwner($user){
            if($user->isGuest) return FALSE;
            if($user->user->isMod) return TRUE;
            $id = Yii::app()->request->getQuery('id');
            $image = Image::model()->findByAttributes(array(
                'id' => $id,
                'user_id' => $user->id,
            ));
            return $image ? TRUE : FALSE;    
        }

        public function init(){

            parent::init();
            //           if(!$this->user){
            //                $userIdentity = new CUserIdentity(6, '');
            //                $userIdentity->setState('id', 6);
            //                $userIdentity->setState('name', 6);
            //                $userIdentity->setState('username', 6);                      
            //                Yii::app()->user->login($userIdentity, 3600*24*365);     
            //            }  
        }


        /**
        * Displays a particular model.
        * @param integer $id the ID of the model to be displayed
        */
        public function actionView($id, $alias = NULL)
        {

            //            echo '<pre>';print_r($this->user);echo '</pre>';die;


            $image = $this->loadModel($id);

            $image->view++;
            $image->update();

            $this->pageTitle = $this->ogTitle = $image->name;
            $this->ogImage = $image->imageThumbUrl;
            if(strlen($image->desc) > 30) $this->pageDesc = $image->desc;

            $this->render('view',array(
                'model'=>$image,
            ));
        }

        public function actionCreate()
        {
            $model=new Image;
            $model->setIsNewRecord(TRUE);

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['Image']))
            {
                $post = $_POST['Image'];
                $model->attributes=$post;
                $model->alias = TextParser::toSEOString($post['name']);
                $model->user_id = $this->user->id;
                $model->status = 'APPROVED';
                $model->created = MyDateTime::getCurrentTime();

                $parser=new CHtmlPurifier();
                $model->desc=$parser->purify($post['desc']);

                if($model->validate()){
                    $model->setIsNewRecord(TRUE);
                    $model->insert();

                    // upload image
                    $this->_postCoverImage($model);

                    // update point
                    if($model->isApproved){
                        $desc_point = (strlen($model->desc) >=120) ? 1 : 0;

                        $attributes = array(
                            'image_count' => 1,
                            'image_desc' => $desc_point,
                        );                 
                        UserAll::model()->updateAttributes($this->user, $attributes);                
                    }


                    Yii::app()->user->setFlash('success', Yii::t('app', 'Image was created successfully.'));

                    $this->redirect($model->url);

                }
            }

            $this->breadcrumbs=array(
                Yii::t('app', 'Images') => $this->createUrl('/web/image/index'),
                Yii::t('app', 'Create'),
            );

            $this->pageTitle = "Đăng ảnh - ".$this->siteSlogan;
            $this->render('create',array(
                'model'=>$model,
            ));
        }

        public function actionFix($id, $crop = 1, $top = false)
        {
            $model = is_object($id) ? $id : $this->loadModel($id);
            $img_cnf = Yii::app()->params->image;
            $post_path = $img_cnf['path'].$model->imageFolder.'/';
            Myext::createDir($post_path);
            Yii::import('ext.wideimage.lib.WideImage');

            $source = $img_cnf['path'].$model->imageFolder.'/'.$model->id.'_original.jpg';
            if(!file_exists($source)){
                if($model->crawl_image){
                    $source = $model->crawl_image;
                }else{
                    $data = $model->getHaivlImageData();
                    $source = $data['img']; 
                }
            }

            $imgObj = WideImage::load($source);
            // remove haivl
            $imgObj = $imgObjThumb = $imgObj->crop(0, -30);

            // add hehe
            $color = 'f2f2f2';
            $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
            $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);
            $watermark = WideImage::load('files/img/image/wm.png');
            $imgObj = $imgObj->merge($watermark, 'left', 'bottom');  

            // crop by crop and top
            $cropVertical = $top ? 30 : -30*($crop+1);
            $imgObj = $imgObj->crop(0, $cropVertical);

            if(!$top){
                $color = 'f2f2f2';
                $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
                $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);
                $watermark = WideImage::load('files/img/image/wm.png');
                $imgObj = $imgObj->merge($watermark, 'left', 'bottom');
            }
            $imgObj->saveToFile($post_path.$model->id.'_original.jpg', 90);


            // save thumb
            $imgObj = $imgObjThumb->resize($img_cnf['thumb']['width'], $img_cnf['thumb']['height'], 'outside', 'down');
            $imgObj = $imgObjThumb->resizeCanvas($img_cnf['thumb']['width'], $img_cnf['thumb']['height'],'center','center', null, 'down');
            $imgObj->saveToFile($post_path.$model->id.'_thumb.jpg', 90);

        }

        public function actionFixImageUrl($folder, $id, $type = 'original'){ // thumb
            //http://hehe.vn/files/image_images/186000/185530_original.jpg
            //http://hehe.vn/upload/image/186000/185530_original.jpg
            $img_cnf = Yii::app()->params->image;
            $folder = Image::model()->getImageFolder($id);
            $url = "{$img_cnf['path']}{$folder}/{$id}_{$type}.jpg";
            //            echo '<pre>';print_r($url);echo '</pre>';die;
            if(file_exists($url)){
                //$this->redirect("/{$url}");

                Yii::import('ext.wideimage.lib.WideImage');
                $imgObj = WideImage::load($url);
                $imgObj->output('jpg', 90);

            }else{
                $this->redirect("/");
            }

        }





        public function actionReviewed($id, $crop = false, $top = false)
        {
            $model=$this->loadModel($id);
            $img_cnf = Yii::app()->params->image;
            $post_path = $img_cnf['path'].$model->imageFolder.'/';
            Myext::createDir($post_path);
            $source = $img_cnf['path'].$model->imageFolder.'/'.$model->id.'_original.jpg';

            if(!file_exists($source)){
                Yii::import('ext.wideimage.lib.WideImage');

                if($model->crawl_image){
                    $source = $model->crawl_image;
                }else{
                    $data = $model->getHaivlImageData();
                    $source = $data['img']; 
                }

                $imgObj = WideImage::load($source);
                // remove haivl
                $imgObj = $imgObjThumb = $imgObj->crop(0, -30);

                // add hehe
                $color = 'f2f2f2';
                $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
                $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);
                $watermark = WideImage::load('files/img/image/wm.png');
                $imgObj = $imgObj->merge($watermark, 'left', 'bottom'); 


                // crop by crop and top
                $cropVertical = $top ? 30 : -30*($crop+1);
                $imgObj = $imgObj->crop(0, $cropVertical);

                if(!$top){
                    $color = 'f2f2f2';
                    $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
                    $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);
                    $watermark = WideImage::load('files/img/image/wm.png');
                    $imgObj = $imgObj->merge($watermark, 'left', 'bottom');
                }
                $imgObj->saveToFile($post_path.$model->id.'_original.jpg', 90);

                // save thumb
                $imgObj = $imgObjThumb->resize($img_cnf['thumb']['width'], $img_cnf['thumb']['height'], 'outside', 'down');
                $imgObj = $imgObjThumb->resizeCanvas($img_cnf['thumb']['width'], $img_cnf['thumb']['height'],'center','center', null, 'down');
                $imgObj->saveToFile($post_path.$model->id.'_thumb.jpg', 90);
            }


            $model->reviewed = MyDateTime::getCurrentTime();
            $model->status = 'APPROVED';
            $model->update();

            if($feed = Feed::model()->findByAttributes(array('image_id' => $model->id))){
                $feed->created = $model->reviewed;
                $feed->update();
            }else{
                $feed = new Feed();
                $feed->image_id = $model->id;
                $feed->created = $model->reviewed;
                $feed->insert();
            }

            if($crop !== false) $this->actionFix($model, $crop, $top);


            return $model;    
        }

        //http://hehe.vn/hehe/web/image/social?id=765
        public function actionSocial($id, $service = 'facebook', $referrer = null)
        {
            $model = $this->actionReviewed($id);

            if($service == 'facebook'){
                $fbPageId = Yii::app()->params->fb['pageId'];

                Yii::import('ext.facebook.src.Facebook');
                $facebook = new Facebook(Yii::app()->params->fb);

                if (!empty($_SESSION['facebook_token'])) {
                    $facebook->setAccessToken($_SESSION['facebook_token']);
                    //                    echo '<pre>session:';print_r($_SESSION['facebook_token']);echo '</pre>';die;
                }elseif(!empty($this->user->emailFacebook->openid_token)){
                    //                    echo '<pre>user:';print_r($this->user->emailFacebook->openid_token);echo '</pre>';die;
                    $_SESSION['facebook_token'] = $this->user->emailFacebook->openid_token;
                    $facebook->setAccessToken($_SESSION['facebook_token']);    
                }


                $openid_id = $facebook->getUser();

                // save access token
                if (isset($_GET['code'])) {
                    $_SESSION['facebook_token'] = $facebook->getAccessToken();

                    $userEmail = UserEmail::model()->findByAttributes(array(
                        'user_id' => $this->user->id,
                        'openid_id' => $openid_id,
                    ));

                    if($userEmail){
                        $userEmail->openid_token = $_SESSION['facebook_token'];
                        $userEmail->update();
                    }else{
                        $attrs = $facebook->api('/me?fields=id,name,birthday,email,gender,link');
                        $userEmail = new UserEmail();
                        $userEmail->user_id = $this->user->id;
                        $userEmail->email = $attrs['email'];
                        $userEmail->openid_id = $openid_id;
                        $userEmail->openid_service = 'FACEBOOK';
                        $userEmail->openid_token = $_SESSION['facebook_token'];
                        $userOpenid->is_main = (isset($this->user->email_main) && $this->user->email_main) ? NULL : 1;
                        $userOpenid->created = MyDateTime::getCurrentTime();
                        $userOpenid->insert();
                    }
                }



                // fb login url
                $fbLoginUrl = $facebook->getLoginUrl(array(
                    'scope' => 'email,user_birthday,publish_stream, manage_pages',
                    'redirect_uri' => $this->createAbsoluteUrl('/hehe/web/image/social', array(
                        'id' => $id,
                        'service' => $service,
                        'referrer' => Yii::app()->request->urlReferrer,
                    )),
                ));
                // check login
                if(!$openid_id){
                    echo json_encode(array('error' => 1, 'url' => $fbLoginUrl));
                    die;
                }

                // check permissons
                $permissions = $facebook->api("/me/permissions");
                if( 
                    !$openid_id || ! array_key_exists('publish_stream', $permissions['data'][0])
                    || ! array_key_exists('manage_pages', $permissions['data'][0])
                ) {
                    echo json_encode(array('error' => 1, 'url' => $fbLoginUrl));
                    die;
                }

                // check manage page
                $pages = $facebook->api(array(
                    'method' => 'fql.query', 
                    'query' => "SELECT page_id, name, page_url FROM page WHERE page_id = {$fbPageId}")
                );

                if(!$pages){
                    echo json_encode(array('error' => 1, 'msg' => 'Bạn không có quyền quản lý page'));
                    die;
                };

                // posts message on page feed
                $msg_body = array(
                    'message' => $model->name,
                    'name' => $model->name,
                    'link' => $model->url,
                    'description' => Yii::app()->controller->siteSlogan,
                    'picture' => $model->imageThumbUrl,
                    'actions' => array(
                        array(
                            'name' => $this->siteName,
                            'link' => $this->baseUrl
                        )
                    )
                );

                //posts message on page statues
                /*
                $msg_body = array(
                'source' => '@'.realpath('myphoto/somephot.gif'),
                'message' => 'message for my wall',
                'published' => 'false', //Keep photo unpublished
                'scheduled_publish_time' => '1333699439' //Or time when post should be published
                );
                */
                $postResult = $facebook->api("/{$fbPageId}/feed", 'post', $msg_body );
                if(isset($postResult['id']) && $postResult['id']){
                    $model->fb_posted = MyDateTime::getCurrentTime();
                    $model->fb_posted_id = $postResult['id'];
                    $model->update();
                }
            }
        }


        private function _postCoverImage(& $model){
            $img_cnf = Yii::app()->params->image;
            $post_path = $img_cnf['path'].$model->imageFolder.'/';


            $post = current($_POST);

            $source = NULL;
            if($post['upload_method'] == 'file'){
                $files = array();
                foreach(current($_FILES) as $key => $value){
                    $files[$key] = $value['image_file'];
                }
                $source = $files;
                $source = $source['size'] ? $source : NULL;
            }else{

                $source = $post['image_url'];
            }


            // BEGIN UPLOAD
            if($source){
                $upload = Myext::uploadImage($source, $post_path, $model->id.'_original', array(
                    'image_resize'              => true,
                    'image_ratio_no_zoom_in'    => true,
                    'image_x'                   => $img_cnf['original']['width'],
                    'image_y'                   => $img_cnf['original']['height'],
                ));
                if($upload->processed){
                    $model->image = $upload->file_dst_name;
                    $model->setIsNewRecord(FALSE);
                    $model->save();

                    // fix haivl && crop
                    if((isset($post['crop_bottom']) && $post['crop_bottom']) || ($post['upload_method'] == 'url' && strpos($post['image_url'], 'haivl.com') !== TRUE))
                    {
                        $params = array(
                            'image_resize' => TRUE,
                            'image_ratio_crop' => 'T',
                            'image_x' => $upload->image_dst_x,
                            'image_y' => $upload->image_dst_y,
                        );
                        if(isset($post['crop_bottom']) && $post['crop_bottom']) $params['image_y'] -= (30*$post['crop_bottom']);
                        if($post['upload_method'] == 'url' && strpos($post['image_url'], 'haivl.com') !== TRUE) $params['image_y'] -= 30;

                        // remove haivl
                        $upload = Myext::uploadImage($post_path.$model->image, $post_path, $model->id.'_original', $params);
                    }

                    // upload thumb
                    Myext::uploadImage($post_path.$model->image, $post_path, $model->id.'_thumb', array(
                        'image_x'                => $img_cnf['thumb']['width'],
                        'image_y'                => $img_cnf['thumb']['height'], 
                        'image_ratio'                => TRUE,
                        'image_resize'                => TRUE,
                        'image_ratio_crop'                => TRUE,
                        'image_ratio_no_zoom_in'                => TRUE, 
                    ));

                    // add hehe   
                    $upload = Myext::uploadImage($post_path.$model->image, $post_path, $model->id.'_original', array(
                        'image_resize' => TRUE,
                        'image_ratio_fill' => 'T',
                        'image_x' => $upload->image_dst_x,
                        'image_y' => $upload->image_dst_y + 30,
                        'image_background_color' => '#f2f2f2',

                        'image_watermark' => 'files/img/image/wm.png',
                        'image_watermark_position' => 'LB',                   
                    ));

                }

            }
        }

        /**
        * Updates a particular model.
        * If update is successful, the browser will be redirected to the 'view' page.
        * @param integer $id the ID of the model to be updated
        */
        public function actionUpdate($id)
        {
            $model=$this->loadModel($id);
            $before_desc = $model->desc;

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['Image']))
            {
                $post = $_POST['Image'];
                $model->attributes=$post;
                $model->alias = TextParser::toSEOString($post['name']);
                if($model->validate()){                
                    $model->setIsNewRecord(FALSE);
                    $model->update();

                    // upload image
                    $this->_postCoverImage($model);

                    // update desc count
                    $attributes = NULL;
                    if(strlen($before_desc) < 120 && strlen($model->desc) >= 120){ // + desc point
                        $attributes = array('image_desc' => 1);
                    }elseif(strlen($before_desc) >= 120 && strlen($model->desc) < 120){ // - desc point
                        $attributes = array('image_desc' => -1); 
                    }
                    if($attributes){
                        UserAll::model()->updateAttributes($model->user, $attributes); 
                    }


                    Yii::app()->user->setFlash('success', Yii::t('app', 'Image was updated successfully.'));

                    $this->redirect($model->url);
                }
            }

            $this->breadcrumbs=array(
                $model->name => $model->url,
                Yii::t('app', 'update'),
            );

            $this->render('update',array(
                'model'=>$model,
            ));
        }

        /**
        * Deletes a particular model.
        * If deletion is successful, the browser will be redirected to the 'admin' page.
        * @param integer $id the ID of the model to be deleted
        */
        public function actionDelete($id)
        {
            $model = $this->loadModel($id);

            Feed::model()->deleteAllByAttributes(array('image_id' => $model->id));

            $img_cnf = Yii::app()->params->image;
            $post_path = $img_cnf['path'].$model->imageFolder.'/';

            Myext::deleteFile($post_path.$model->id."_original.jpg");
            Myext::deleteFile($post_path.$model->id."_thumb.jpg");

            $model->delete();


            if($model->fb_posted_id){

                $fbPageId = Yii::app()->params->user['fb']['pageId'];

                Yii::import('ext.facebook.src.Facebook');
                $fb = new Facebook(array(
                    'appId'  => Yii::app()->params->user['fb']['appId'],
                    'secret' => Yii::app()->params->user['fb']['secret'],
                ));

                $fb_id = $fb->getUser();

                // check login
                $fbLoginUrl = $fb->getLoginUrl(array(
                    'scope' => 'publish_stream,manage_pages',
                    'redirect_uri' => Yii::app()->request->getBaseUrl(TRUE).Yii::app()->request->requestUri,
                ));
                if(!$fb_id){
                    Yii::app()->controller->redirect($fbLoginUrl);
                }

                // check permissons
                $permissions = $fb->api("/me/permissions");
                if( 
                    !$fb_id || ! array_key_exists('publish_stream', $permissions['data'][0])
                    || ! array_key_exists('manage_pages', $permissions['data'][0])
                ) {
                    Yii::app()->controller->redirect($fbLoginUrl);
                }


                $fb->api("/{$model->fb_posted_id}","DELETE");
            }

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            //            if(!isset($_GET['ajax']))
            //                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/'));
        }


        /**
        * output image by id
        * @link http://hehe.vn/web/image/img?id=1
        * @param mixed $id
        */
        public function actionImg($id){
            Yii::import('ext.wideimage.lib.WideImage'); 
            Yii::app()->params->image;

            $image = Image::model()->findByPk($id);
            if(!$image) return;

            /*
            if(!$image->crawl_image){

            $data = $image->getHaivlImageData();
            if(!$data){
            $image->delete();
            return;
            }

            if($data['youtube']){
            if(!Video::model()->exists("youtube = {$data['youtube']}")){
            $video = new Video();
            $video->name = $data['name'];
            $video->alias = TextParser::toSEOString($data['name']);
            $video->youtube = $data['youtube'];

            $video->user_id = $user_id ? $user_id : User::model()->getRandomUserId();
            $video->status = 'APPROVED';
            $video->created = $data['created'];
            $video->crawl = "haivl";
            $video->crawl_id = $image->crawl_id;

            $video->setIsNewRecord(TRUE);
            $video->insert(); 
            unset($video); 

            $image->delete();
            }

            return;
            }

            $image->crawl_image = $data['img'];
            $image->update();

            }
            */
            $data = $image->getHaivlImageData();
            if(!isset($data['img']) || !$data['img']){
                //                $image->delete();
                return;
            }

            $imgObj = WideImage::load($data['img']);
            //$imgObj = WideImage::load($image->crawl_image);
            // remove haivl
            $imgObj = $imgObjThumb = $imgObj->crop(0, -30);

            // add hehe and save
            $color = 'f2f2f2';
            $allocateColor = $imgObj->allocateColor(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
            $imgObj = $imgObj->resizeCanvas('100%', '100%+30', 0, 0, $allocateColor);
            $watermark = WideImage::load('files/img/image/wm.png');
            $imgObj = $imgObj->merge($watermark, 'left', 'bottom');
            $imgObj->output('jpg', 90);
        }

        /**
        * Danh sách images
        * 
        * @param string $username username
        * @param string $type hiển thị theo kiểu: NULL: đã review lên top. 'review' : Chưa review lên top
        */
        public function actionIndex($username = NULL, $type = 'ok')
        {   
            $title = 'Ảnh vui';

            $criteria=new CDbCriteria;
            if($type == 'ok'){
                $criteria->addCondition("t.`status` = 'APPROVED'");
                $criteria->order = "t.reviewed DESC";
            }
            elseif($type == 'review'){
                $criteria->addCondition("t.`reviewed` is NULL");
                $criteria->order = "t.id DESC";
                $title = 'Duyệt ảnh';
            }


            if($username){
                $user = User::model()->findByAttributes(array('username' => $username));
                if(!$user)   throw new CHttpException(404,'The requested page does not exist.');
                $criteria->addCondition("t.user_id = {$user->id}");

                $title = 'Ảnh đăng bởi '.$user->name;
                $this->pageTitle = "{$title} | ". $this->siteSlogan;
            }

            $this->menu_selected = 'image';
            $dataProvider = new CActiveDataProvider('Image', array(
                'criteria'=>$criteria,
                'pagination' => array(
                    'pageSize' => 10,
                    'pageVar' => 'page',
                ),
            ));

            $this->pageTitle = "{$title} | ". $this->siteSlogan;

            $this->render('index', compact('dataProvider', 'title'));
        }

        /**
        * Manages all models.
        */
        public function actionAdmin()
        {
            $model=new Image('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Image']))
                $model->attributes=$_GET['Image'];

            $this->render('admin',array(
                'model'=>$model,
            ));
        }

        /**
        * Returns the data model based on the primary key given in the GET variable.
        * If the data model is not found, an HTTP exception will be raised.
        * @param integer the ID of the model to be loaded
        */
        public function loadModel($id)
        {
            $model=Image::model()->findByPk($id);
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }

        /**
        * Performs the AJAX validation.
        * @param CModel the model to be validated
        */
        protected function performAjaxValidation($model)
        {
            if(isset($_POST['ajax']) && $_POST['ajax']==='image-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
        }


        public function actionAjaxUpdatePoint(){


            $response = Yii::app()->request->getParam('response');
            $event = Yii::app()->request->getParam('event');


            if($event == 'like'){
                $url = $response; //if like fanpage ? https://www.facebook.com/www.hehe.vn : http://hehe.vn/i/131741
                $imgId = substr($url, 17);
                if(is_numeric($imgId)){ // if like image, not fanpage
                    $image = Image::model()->findByPk($imgId);    
                    $image->fb_like_count += 1;
                    $image->update();    
                }     
            }elseif($event == 'unlike'){
                $url = $response;
                $imgId = substr($url, 17);
                if(is_numeric($imgId)){
                    $image = Image::model()->findByPk($imgId);  
                    $image->fb_like_count -= 1;
                    $image->update();    
                }   

            }elseif($event == 'comment'){
                $url = $response['href'];
                $imgId = substr($url, 17);
                $image = Image::model()->findByPk($imgId);  
                $image->fb_comment_count += 1;
                //                echo '<pre>';print_r($image->attributes);echo '</pre>';die;
                $image->update();    

            }elseif($event == 'uncomment'){
                $url = $response['href'];
                $imgId = substr($url, 17);
                $image = Image::model()->findByPk($imgId);  
                $image->fb_comment_count -= 1;
                $image->update();
            }


            // update user
        }


    }
